package com.ymt.reliable.message.queue.rabbitmq.service.impl;

import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConditionalOnProperty(prefix = "rabbitMq", name = "host", matchIfMissing = false)
public class RabbitMqConfig {
    @Value("${rabbitMq.host}")
    private String host;
    @Value("${rabbitMq.port}")
    private Integer port;
    @Value("${rabbitMq.username}")
    private String username;
    @Value("${rabbitMq.password}")
    private String password;

    @Bean(name = "rabbitMqConnectionFactory")
    public CachingConnectionFactory cachingConnectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(username);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

    @Bean
    public RabbitTemplate rabbitTemplate(CachingConnectionFactory connectionFactory) {
        RabbitTemplate template = new RabbitTemplate();
        template.setConnectionFactory(connectionFactory);
        return template;
    }
}
